#!/usr/bin/env python
#
# Simple packaging script for creating a release zip. Initially
# this will probably just zip up the contents of a specified folder
# however in future it will likely do more.
#

import os, sys
import zipfile, shutil

# Process args
path  = os.path.abspath(sys.argv[1])
ver   = sys.argv[2]
name  = os.path.basename(path)
addon = os.path.join(path, 'addon.xml')
if not os.path.isdir(path) or not os.path.isfile(addon):
  print 'ERROR: invalid path specified'

# Zip the folder
zn = '%s-%s.zip' % (name, ver)
print 'write %s' % zn
zp = zipfile.ZipFile(zn, 'w', compression=zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(path):
  if '.svn' in root: continue
  a = root.replace(path, name)
  for f in files:
    p = os.path.join(root, f)
    f = os.path.join(a, f)
    print '  %s' % f
    zp.write(p, f, zipfile.ZIP_DEFLATED)
zp.close()
print 'done'

# Install it
if len(sys.argv) > 3:
  dest = os.path.join(os.path.abspath(sys.argv[3]), name)
  if not os.path.isdir(dest):
    os.makedirs(dest)

  # Install the zip file
  print 'install zip...'
  shutil.copy(zn, os.path.join(dest, zn))

  # Install addon.xml
  print 'install addon.xml'
  shutil.copy(addon, os.path.join(dest, 'addon.xml'))

  # Install changelog
  p = os.path.join(path, 'changelog.txt')
  if os.path.isfile(p):
    print 'install changelog...'
    shutil.copy(p, os.path.join(dest, 'changelog-%s.txt' % ver))

  # Install icon.png
  p = os.path.join(path, 'icon.png')
  if os.path.isfile(p):
    print 'install icon.png'
    shutil.copy(p, os.path.join(dest, 'icon.png'))

  # Install fanart.jpg
  p = os.path.join(path, 'fanart.jpg')
  if os.path.isfile(p):
    print 'install fanart.jpg'
    shutil.copy(p, os.path.join(dest, 'fanart.jpg'))
